package com.guigu.qingcheng.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.guigu.qingcheng.excption.GuliException;
import com.guigu.qingcheng.mapper.TbUserMapper;
import com.guigu.qingcheng.pojo.TbUser;
import com.guigu.qingcheng.pojo.vo.NewuserVo;
import com.guigu.qingcheng.service.TbUserService;
import com.guigu.qingcheng.utils.JwtUtils;
import com.guigu.qingcheng.utils.MD5;
import com.guigu.qingcheng.utils.PageUtil;
import com.guigu.qingcheng.utils.R;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.TimeUnit;


/**
*
* @author Jiang
* @date 2020/08/05
*/
@Service
public class TbUserServiceImpl implements TbUserService {
    @Autowired(required = false)
    private TbUserMapper tbUserMapper;

    @Autowired(required = false)
    private AmqpTemplate amqpTemplate; // rabbitmq 的template

    @Autowired
    private RedisTemplate redisTemplate; // redis 的 template

    @Override
    public Map findnewuser(NewuserVo newuserVo) {
        return tbUserMapper.findnewuser(newuserVo);
    }

    @Override
    public Map finduser() {
        return tbUserMapper.finduser();
    }

    @Override
    public List<TbUser> queryAll() {
        List<TbUser> tbUser = tbUserMapper.selectAll();
            return tbUser;
    }
    @Override
    public TbUser findById(Integer id) {
        return tbUserMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageUtil<TbUser> findListAll(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        Page<TbUser> pages = (Page<TbUser>) tbUserMapper.selectAll();
        PageUtil<TbUser> pageUtil=new PageUtil<>();
        pageUtil.setRows(pages.getResult());
        pageUtil.setTotal(pages.getTotal());
        return pageUtil;
    }


    @Override
    public PageUtil<TbUser> pageQueryByAll(Integer pageNum, Integer pageSize, TbUser tbUser) {

        Example example=new Example(TbUser.class);
        Example.Criteria criteria = example.createCriteria();
        // TODO 待实现 重新实现判断参数

        if(!StringUtils.isEmpty(tbUser.getUsername())){
            criteria.andLike("username","%"+tbUser.getUsername()+"%");
        }
        if(!StringUtils.isEmpty(tbUser.getUserLevel())){
           criteria.andLike("userLevel","%"+tbUser.getUserLevel()+"%");
        }
        if(!StringUtils.isEmpty(tbUser.getCreated())){
            criteria.andGreaterThanOrEqualTo("created",tbUser.getCreated());
            LocalDate date = tbUser.getCreated().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().plusDays(1);
            criteria.andLessThan("created",date);
        }
        PageHelper.startPage(pageNum,pageSize);
        Page<TbUser> pages = (Page<TbUser>) tbUserMapper.selectByExample(example);
        PageUtil<TbUser> pageUtil=new PageUtil<>();
        pageUtil.setRows(pages.getResult());
        pageUtil.setTotal(pages.getTotal());
        return pageUtil;
     }


    @Override
    public boolean saveTbUser(TbUser tbUser) {
        int insert = tbUserMapper.insert(tbUser);
        if(insert>0){
            return true;
        }
        return false;
    }

    @Override
    public boolean updateTbUser(TbUser tbUser) {
        int i = tbUserMapper.updateByPrimaryKeySelective(tbUser);
        if(i>0){
            return true;
        }
        return false;
    }


    @Override
    public boolean deleteById(String username) {
        Example example = new Example(TbUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username",username);
        int i = tbUserMapper.deleteByExample(example);
        if(i>0){
            return true;
        }
        return false;
    }

    @Override
    public TbUser findById(String username) {
        return tbUserMapper.selectByPrimaryKey(username);
    }


    /**
     * 生成验证码
     * @param mobile
     */
    @Override
    public void sendSms(String mobile) {
        // 生成满足条件的验证码
        int max=999999;
        int min=100000;
        Random random = new Random();
        int code = random.nextInt(max);
        if(code<min){
            code=code+min;
        }

        // 保存到redis
        redisTemplate.boundValueOps("code_"+mobile).set(code+"");
        redisTemplate.boundValueOps("code_"+mobile).expire(5,
                TimeUnit.MINUTES);//5分钟失效

        // 发送到rabbitmq的队列中
        Map<String,String> map=new HashMap();
        map.put("phone", mobile);
        map.put("code", code+"");
        amqpTemplate.convertAndSend("","queue.sms",
                JSON.toJSONString(map));
    }

    /**
     * 添加用户
     * @param tbUser
     * @param smsCode
     */
    @Override
    public void add(TbUser tbUser, String smsCode) {
        //比较短信验证码
        //获取系统短信验证码
        String sysCode= (String)
                redisTemplate.boundValueOps("code_"+tbUser.getPhone()).get();
        if(sysCode==null){
            throw new RuntimeException("验证码未发送或已过期");
        }
        if(!smsCode.equals(sysCode)){
            throw new RuntimeException("验证码不正确");
        }

        if(tbUser.getUsername()==null){
            tbUser.setUsername(tbUser.getPhone());
        }
        TbUser searchUser=new TbUser();
        searchUser.setUsername(tbUser.getUsername());
        if(tbUserMapper.selectCount(searchUser)>0) { //查询是否存在相同记录
            throw new RuntimeException("该手机号已注册");
        }
        tbUser.setNickName(tbUser.getUsername());//设置昵称默认等于用户名
        tbUser.setCreated(new Date());
        tbUser.setUpdated(new Date());
        tbUser.setPoints(0);//积分初始值为0
        tbUser.setStatus("1");//状态1
        tbUser.setIsEmailCheck("0");//邮箱认证
        tbUser.setIsMobileCheck("1");//手机认证
        tbUser.setUserLevel(0);//默认会员等级
        tbUserMapper.insert(tbUser);
    }
    /**
     * 登录
     * @param tbUser
     * @return
     */
    @Override
    public String login(TbUser tbUser) {
        // 获取登录手机和密码
        String mobile = tbUser.getPhone();
        String password = tbUser.getPassword();

        // 手机号和密码非空判断
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)) {
            return "手机号或者密码为空！！！";
        }

        // 判断手机号是否正确
        Example example = new Example(TbUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("phone", mobile);
        List<TbUser> users = tbUserMapper.selectByExample(example);
        if(users.size()==0) {
            return "手机号或者密码不正确！！！";
        }

        // 登录成功的用户
        TbUser member = users.get(0);

        // 判断密码
        // 因为存储到数据库密码是加密的
        // 把输入的密码进行加密，再和数据库密码进行比较
        // 加密方式MD5
        if(!MD5.encrypt(password).equals(member.getPassword()))
            return "手机号或者密码不正确！！！";

        // 登录成功
        // 生成token字符串，使用jwt工具类
        String jwtToken = JwtUtils.getJwtToken(member.getUsername(), member.getNickName());
        return jwtToken;
    }
    @Override
    public TbUser getByOpenid(String openid) {
        Example example = new Example(TbUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("openid", openid);
        List<TbUser> users = tbUserMapper.selectByExample(example);
        if(users.size()>0)
            return users.get(0);
        return null;
    }

    @Override
    public void updatePasswordByUsername(TbUser user) {
        Example example = new Example(TbUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", user.getUsername());
        String password = user.getPassword();
        String encrypt = MD5.encrypt(password);
        user.setPassword(encrypt);
        int i = tbUserMapper.updateByExampleSelective(user, example);
        if (i < 1) {
            throw new RuntimeException("修改密码失败");
        }
    }
}
